if (!$.cookie('token')) {
    window.location.href = './shopunknwo.html'
}

class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            thumburl: '',
            isnew: GetQueryString('isnew') == 0,
            inventory: 50,
            postfee: 0,
            postamount: 0,
            color: '',
            state: 1,
            filecode: 0,  //0封面图 1详情图 2轮播图
            id: 0,
            describe: '',            
            name: '',
            finishupload: !1,
            uploadword: '上传',
            btntypehtml:[],
            btnchecklist:[],
            imglist: [],
            score:0,
            detailimg: [],
            detailimglist: [], //存的是base64数组
            swiperimg: [],
            swiperimglist: []//存的是base64数组
        };
    }

    clickupload(e) {
        console.log(e, 'clickupload');
        this.setState({
            filecode: e
        }, () => { $('#file').click(); })
    }
    getbtntypehtml(cb){
        let {btntypehtml} = this.state;
         getmainbtns(res=>{
           if(res.issuccess==1){
               let btns = JSON.parse(res.btns);              
               if(btns.length>0){
                   btns.forEach((x,i)=>{
                    btntypehtml.push(
                        <div  key={i}>
                            <span>{x.name}</span>
                            <input id={x.name} type='checkbox' onClick={this.changebtntype.bind(this,x.name)} />
                        </div>
                    )
                   })
              
                   this.setState({originbtns:btns,btntypehtml},()=>{
                       cb&&cb()
                   })
               }
           }     
    })

    }

    //type 0头图 1详情图 2轮播图
    putlistdata(type, target) {
        var that = this;
        target.forEach((x, i) => {
            if (type == 0) {
                that.setState({ thumburl: x })
            } else {
                var base64prop = 'detailimglist'
                    , prop = 'detailimg'
                    , list = that.state[prop]
                    , src = x
                    , onclicktap = that.del_detail_img.bind(that, list.length);
                if (type == 2) {
                    base64prop = 'swiperimglist';
                    prop = 'swiperimg';
                    list = that.state[prop];
                    onclicktap = that.del_swiper_img.bind(that, list.length);
                }
                if (!isBase64(src)) {
                    if (src.indexOf(`${API_HEAD}`) == -1) {
                        src = `${API_HEAD}imgs/${src}`
                    }
                }
                var base64list = that.state[base64prop];
                base64list.push(src);
                list.push(
                    <div className={prop + "_div index" + list.length} key={list.length}>
                        <img key={list.length} src={src} className="img-responsive" />
                        <img key={"close_" + list.length} className='closeimg' onClick={onclicktap} src='./src/img_close.png' />
                    </div>
                )
                that.setState({
                    [base64prop]: base64list,
                    [prop]: list
                })
            }
        });

    }


    changebtntype(name){
        let {btnchecklist}=this.state;
        console.log('btnchecklist',btnchecklist);      
        console.log(btnchecklist.indexOf(name)>-1,'btnchecklist.indexOf(name)>-1');
        
        if(btnchecklist.indexOf(name)>-1){
            let index = btnchecklist.indexOf(name);
            btnchecklist.splice(index,1);
            $('#'+name).attr('checked',false);
        }else{
            btnchecklist.push(name); 
            $('#'+name).attr('checked',true);
        }
        console.log(btnchecklist,'btnchecklist');
        this.setState({btnchecklist});

    }

    filechange(e) {
        this.setState({
            finishupload: !1,
            uploadword: "上传"
        })
        var that = this;
        var filecode = this.state.filecode;
        console.log(filecode, 'filecode');
        var filedata = $('#file')[0].files[0];

        var reader = new FileReader();
        reader.readAsDataURL(filedata);
        reader.onload = function (e) {
        var base64str = e.target.result;
        that.putlistdata(filecode, [base64str]); 
        }
    }

    //

    del_detail_img(e) {
        var that = this;
        if (e == -1) {
            //删除封面图
            this.setState({
                thumburl: '',
                thumburl: ''
            })
            return;
        }
        console.log('delete e', e);

        var detailimg = [];
        var detailimglist = this.state.detailimglist;
        detailimglist.splice(e, 1);
        detailimglist.forEach((x, i) => {
            detailimg.push(
                <div className={"detailimg_div index" + i} key={i}>
                    <img key={i} src={x} className="img-responsive" />
                    <img key={"close_" + i} className='closeimg' onClick={that.del_detail_img.bind(that, i)} src='./src/img_close.png' />
                </div>
            )
        })
        that.setState({
            detailimg,
            detailimglist,

        })

    }


    del_swiper_img(e) {
        var that = this;
        var swiperimg = [];
        var swiperimglist = this.state.swiperimglist;
        swiperimglist.splice(e, 1);
        swiperimglist.forEach((x, i) => {
            swiperimg.push(
                <div className={"detailimg_div index" + i} key={i}>
                    <img key={i} src={x} className="img-responsive" />
                    <img key={"close_" + i} className='closeimg' onClick={that.del_swiper_img.bind(that, i)} src='./src/img_close.png' />
                </div>
            )
        })
        that.setState({
            swiperimg,
            swiperimglist,

        })

    }


    doupload(type, list) {
        var that = this, newlist = list;
        list.forEach((x, i) => {
            if (isBase64(x)) {
                uploadimg(x, res => {
                    if (res.issuccess == 1) {
                        if (type == 0) {
                            that.setState({ thumburl: `${API_HEAD}imgs/${res.path}` })
                            return;
                        } else {
                            newlist[i] = `${res.path}`;
                            $(`.${type == 1 ? 'detail' : 'swiper'}img_div.index${i} .img-responsive`).attr('src', `${API_HEAD}imgs/${res.path}`)
                        }
                    } else {
                        alert(res.msg);
                        return;
                    }
                })
            }
        });
        if (type != 0) {
            var prop = `${type == 1 ? 'detail' : 'swiper'}imglist`;
            that.setState({ [prop]: newlist })
        }

    }

    upload() {
        var that = this
            , reallist = []
            , { thumburl, detailimglist, swiperimglist } = this.state;
        if (thumburl.length > 0 && isBase64(thumburl)) {  //封面图
            that.doupload(0, [thumburl]);
        }
        if (detailimglist.length > 0) {
            that.doupload(1, detailimglist)
        }
        if (swiperimglist.length > 0) {
            that.doupload(2, swiperimglist)
        }
        that.setState({
            uploadword: `上传成功`,
            finishupload: !0
        })

    }



    submit() {
        var { thumburl, price,describe, cid, score,code,unit,kc,btnchecklist, state, name, swiperimglist, detailimglist, finishupload } = this.state
            , err = '';     
        
        //   if(detailimglist.length==0) err = '请添加详情图片';
        //   if(swiperimglist.length==0) err = '请添加轮播图片';
        if (thumburl.length == 0) err = '请添加头图';
        if (describe.length == 0) err = '请填写描述';
        if (!finishupload) err = '请上传图片';
        console.log(color, 'color');

        if (code.length == 0) err = '请填写商品编码';
        if (kc.length == 0) err = '请填写库存';
        if (unit.length == 0) err = '请填写计量描述';
        // if(Number(inventory)<=0||isNaN(inventory)) err = '请正确填写库存';
        if (Number(price) <= 0 || isNaN(price)) err = '请正确填写价格';

        // if(Number(inventory)<=0||isNaN(inventory)) err = '请正确填写库存';
        if (Number(score) <= 0 || isNaN(score)) err = '请正确填写积分';
        // if(Number(postamount)<0||isNaN(postamount)) err = '请正确填写包邮额度';
        // if(Number(postfee)<0||isNaN(postfee)) err = '请正确填写邮费';
        if (name.length == 0) err = '请填写姓名';
        if (err.length > 0) {
            alert(err);
            return;
        }
        swiperimglist = swiperimglist.join(',');
        detailimglist = detailimglist.join(',')




        //   if(describe.length==0) err = '物品描述不能为空';
        //   if(thumbPicPath.length==0) err = '请上传图片';
        //   if(isNaN(inventory)||Number(inventory)<=0) err = '库存有误';
        //   if(isNaN(price)||Number(price)<=0) err = '单价有误';
        //   if(name.length==0) err = '姓名不能为空';
        //   if(err.length>0) {alert(err);return}
        var submitdata = {
            thumbPicPath: thumburl, state, cid, describe, name, score, color, swiperimglist
            , detailimglist
        }
        if (this.state.id > 0) submitdata['id'] = this.state.id;
        addsgoods(submitdata, res => {
            if (res.issuccess == 1) {
                alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                // window.location.href='./main.html'
            }
        })
    }



    componentDidMount() {
        var id = GetQueryString("id");
        var that = this;

        // getcategorylist(res => {
        //     if (res.issuccess == 1) {
        //         var cid = res.list[0]['id'];
        //         var categoryhtml = [];
        //         res.list.forEach((x, i) => {
        //             categoryhtml.push(
        //                 <option key={i} value={x.id}>{x.name}
        //                 </option>
        //             )
        //         })
        //         that.setState({ categoryhtml, cid })
        //     }
        // })
        getcoupons(res=>{
            if (res.issuccess == 1) {
                if(res.list.length==0){
                    this.setState({nocoupon:!0})
                }else{
                    var couponhtml = [];
                    couponhtml.push(
                        <option key={-1} value={0}>无
                        </option>
                    )
                    res.list.forEach((x, i) => {
                        let zhe = x.percents%10==0?x.percents/10:parseFloat(x.percents/10).toFixed(1), yhxs = x.type==0
                ?(x.threshold==0?`全场减${x.reduce/100}元`:`满${x.threshold/100}减${x.reduce/100}元`)
                :(x.threshold==0?`全场${zhe}折`:`满${x.threshold/100}打${zhe}折`)
                        couponhtml.push(
                            <option key={i} value={x.id}>{yhxs}
                            </option>
                        )
                    }) 
                    that.setState({ couponhtml })
                }
            }
        })
        this.getbtntypehtml(()=>{
            if (id != '0' && id != "null") {
                this.state.id = id;
                getsdetail({ id }, res => {
                    console.log('res', res);
    
                    if (res.issuccess == 1) {
                        var goods = res.goods;
                        if (goods.detaillist != null && goods.detaillist.length > 0) {
                            that.putlistdata(1, goods.detaillist.split(','))
                        }
                        if (goods.swiperlist != null && goods.swiperlist.length > 0) {
                            that.putlistdata(2, res.goods.swiperlist.split(','))
                        }
    
                        this.setState({
                            thumburl: goods.thumbPicPath,
                            finishupload: !0,
                            state: goods.state,
                            describe: goods.describe,
                            name: goods.name,
                            cid: goods.categoryid,
                           
                            postfee: goods.postfee,
                            postamount: goods.postamount,
                            score: goods.score ,
                            price: Number(goods.price) / 100,
                            code: goods.code ,
                            unit:goods.unit,
                            kc: goods.kc,
                        })
                    } else {
                        alert('商品不存在')
                        window.location.href = './goodsmain.html'
                    }
    
                })
    
            }
        });
        

    }

    inputchange(e, x) {
        console.log(e, 'e');
        console.log(x, 'x');
        var prop = e == 0 ? 'name' :
         e == 1 ? "score" :
         e == 2 ? "postfee" : 
         e == 3 ? "describe" :         
         e == 4 ? "code" :
         e == 5 ? "unit" :
         e==6?'price':
         e==7?'kc':
         'postamount'
        this.setState({
            [prop]: x.target.value
        })
    }
    statechange(e) {
        console.log(e);
        this.setState({
            state: e
        })

    }
    oncouponchange(e){
        console.log(e.target.value,'oncouponchange');
        
        this.setState({ cancoupon: e.target.value })
    }
    oncategorychange(e) {
        console.log(e.target.value, 'changegg');
        this.setState({ cid: e.target.value })
    }
    del() {
        $('#myModal').modal('toggle');
    }
    confirmdel() {
        delsgoods(this.state.id, res => {
            if (res.issuccess == 1) {
                window.location.href = './scoremain.html'
            }

        })
    }
    render() {

        //  <img style={{display:this.state.thumburl.length>0?"block":"none"}} src={this.state.thumburl} className="img-responsive"  /> 
        let {btntypehtml} = this.state;
        return (
            
            <div>
                <Modal content='确定删除吗？' click={this.confirmdel.bind(this)} />
                <div className='content_wrap panel-default content_wrap'>
                    <div className='breadLine '>
                        当前位置 > 积分商品管理 > {this.state.id == 0 ? "新建" : "编辑"}积分商品
                    </div>
                    <div className='inputs panel-body'>
                        <h3>{this.state.id == 0 ? "新建" : "编辑"}积分商品</h3>
                        <div className="input-group">
                            <span className="input-group-addon">商品名称</span>
                            <input id='name' onChange={this.inputchange.bind(this, 0)} value={this.state.name} type="text" placeholder='请输入商品名称' className="form-control" />
                        </div>
                        {/* 添加 */}
                        <div className="input-group input-group">
                            <span className="input-group-addon ">单价</span>
                            <input id='price' onChange={this.inputchange.bind(this, 6)} value={this.state.price} type="text" placeholder='请输入单价' className="form-control kc" />
                        </div>
                        <div className="input-group input-group">
                            <span className="input-group-addon ">购买所需积分</span>
                            <input id='score' onChange={this.inputchange.bind(this, 1)} value={this.state.score} type="text" placeholder='请输入单价' className="form-control kc" />
                        </div>
                        {/* 添加 */}
                        <div className="input-group input-group">
                            <span className="input-group-addon ">商品编码</span>
                            <input id='color' onChange={this.inputchange.bind(this, 4)} type="text" value={this.state.code} placeholder='请输入商品编码' className="form-control " />
                        </div>
                        {/* <div className="input-group input-group">
<span className="input-group-addon ">邮费</span>
<input id='postfee' onChange={this.inputchange.bind(this,2)}type="text" value={this.state.postfee} placeholder='请输入库存' className="form-control kc" />
</div> 

 <div className="input-group input-group">
<span className="input-group-addon ">包邮额度</span>
<input id='postamount' onChange={this.inputchange.bind(this,5)}type="text" value={this.state.postamount} placeholder='请输入库存' className="form-control kc" />
</div>  */}
                        {/* 添加 */}
                        <div className="input-group input-group">
                            <span className="input-group-addon ">计量描述</span>
                            <input  onChange={this.inputchange.bind(this, 5)} type="text" value={this.state.unit} placeholder='请输入商品计量描述' className="form-control " />
                            
                        </div>
                        {/* 添加 */}
                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">库存</span>
                            <input  onChange={this.inputchange.bind(this, 7)} type="text" value={this.state.kc} placeholder='请输入商品库存' className="form-control " />
                        </div>
                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">商品描述</span>
                            <textarea id='describe' onChange={this.inputchange.bind(this, 3)} value={this.state.describe} style={{ height: "30vh" }} className="form-control" placeholder='请输入商品描述' rows="3"></textarea>
                        </div>
                        {/* 添加 */}
                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">按钮组类型</span>
                            <div className='btntype'>
                            {btntypehtml}
                            </div>
                        </div>
                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">商品状态</span>
                            <div>
                                <label className="radio-inline">
                                    <input type="radio" id="inlineCheckbox1" onChange={this.statechange.bind(this, 0)} checked={this.state.state == 0} value="0" /> 上架
                                </label>
                                <label className="radio-inline">
                                    <input type="radio" id="inlineCheckbox2" onChange={this.statechange.bind(this, 1)} checked={this.state.state == 1} value="1" /> 下架
                                </label>
                                <label className="radio-inline">
                                    <input type="radio" id="inlineCheckbox3" onChange={this.statechange.bind(this, 2)} checked={this.state.state == 2} value="2" /> 售完
                                </label>
                            </div>
                        </div>


                        <div className="input-group">
                            <span className="input-group-addon desc">选择类型</span>
                            <select value={this.state.cid} onChange={this.oncategorychange.bind(this)} className="form-control select">
                                {this.state.categoryhtml}
                            </select>
                        </div>


                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">上传封面图</span>
                            <input onChange={this.filechange.bind(this)} type='file' id='file' />
                            <div className='img_warp' >
                                <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, 0)} style={{ display: this.state.thumburl.length > 0 ? "none" : "" }} />
                                <img style={{ display: this.state.thumburl.length > 0 ? "block" : "none" }} src={this.state.thumburl} className="img-responsive" />
                                <img className='closeimg thumb' style={{ display: this.state.thumburl.length > 0 ? "block" : "none" }} onClick={this.del_detail_img.bind(this, -1)} src='./src/img_close.png' />
                            </div>

                        </div>

                        <div className="input-group input-group imgs">
                            <span className="input-group-addon desc">上传详情图</span>
                            <input onChange={this.filechange.bind(this)} type='file' id='file' />
                            <div className='detail_btns'>
                                <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, 1)} />
                                <div className='img_warp' >
                                    {this.state.detailimg}
                                </div>

                            </div>
                        </div>

                        <div className="input-group input-group imgs">
                            <span className="input-group-addon desc">上传轮播图</span>
                            <input onChange={this.filechange.bind(this)} type='file' id='file' />
                            <div className='detail_btns'>
                                <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, 2)} />
                                <div className='img_warp' >
                                    {this.state.swiperimg}
                                </div>

                            </div>
                        </div>


                        <div className='btns_bottom center'>
                            <div style={{ display: this.state.thumburl.length > 0 ? "flex" : "none" }} className='btn_upload'>
                                <button onClick={this.upload.bind(this)}
                                    className={`btn add btn-${this.state.finishupload ? "success" : "primary"} center w20`} id='btnimg_save'>{this.state.uploadword}</button>

                            </div>
                            <button className='btn add btn-primary center w20' onClick={this.submit.bind(this)} id='btnimg_save'>保存</button>
                            <button onClick={this.del.bind(this)} style={{ display: this.state.id == 0 ? "none" : "" }} className='btn add btn-danger center w20' >  删除</button>
                        </div>
                    </div>
                </div>
            </div>

        )
    }
}


ReactDOM.render(
    <div>
        <TopLine />
        {/* <LeftMenu code='8' /> */}
        <LeftMenu code='scoregoods' />
        <Main />
    </div>
    , $('.container')[0]
)